package com.ruoyi.api.web;


import cn.binarywang.wx.miniapp.api.WxMaService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.github.binarywang.wxpay.service.WxPayService;
import com.ruoyi.api.vo.CartVo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.shop.domain.*;
import com.ruoyi.shop.domain.vo.ShopCouponVo;
import com.ruoyi.shop.domain.vo.ShopProductSimpleVo;
import com.ruoyi.shop.service.*;
import com.ruoyi.shop.util.pay.UserOrderItemConstants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "API商城接口")
@RestController
@RequestMapping("/api/base")
public class ApiShopBaseController extends ApiBaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IShopAdService shopAdService;
    @Autowired
    private IShopProductCategoryService shopProductCategoryService;
    @Autowired
    private IShopProductService shopProductService;
    @Autowired
    private IShopProductImageService shopProductImageService;
    @Autowired
    private IShopUserFavoriteService shopUserFavoriteService;
    @Autowired
    private IShopProductCommentService shopProductCommentService;
    @Autowired
    private IShopUserCartService shopUserCartService;
    @Autowired
    private IShopCouponService shopCouponService;

    @Autowired
    private WxPayService wxService;
    @Autowired
    private WxMaService wxMaService;

    @ApiOperation("获取可用的广告")
    @ApiImplicitParam(paramType = "header",name = "token", value = "用户token",required = true, dataType = "String")
    @GetMapping("/ad")
    public AjaxResult adList()
    {
        getToken();
        String appid = wxMaService.getWxMaConfig().getAppid();
        ShopAd param = new ShopAd();
        param.setEnabled(1);
        List<ShopAd> adList = shopAdService.selectShopAdList(param);
        return AjaxResult.success(adList);
    }

    /**
     * 商品搜索
     */
    @ApiOperation(value = "商品搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "token", value = "用户token",required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "pageSize", value = "数量", dataType = "Integer"),
            @ApiImplicitParam(paramType = "query",name = "pageNum", value = "页码", dataType = "Integer"),
            @ApiImplicitParam(paramType = "query",name = "keyword", value = "关键字", dataType = "Integer"),
    })
    @GetMapping("/search/goods")
    public AjaxResult searchGoodsList(String keyword){

        if(StringUtils.isEmpty(keyword)){
            return AjaxResult.error("请输入关键字");
        }
        startPage();
        List<ShopProductSimpleVo> list = shopProductService.selectShopProductByTitle(keyword);
        return AjaxResult.success(list);
    }

    /**
     * 领券中心
     */
    @ApiOperation(value = "领券中心")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "token", value = "用户token",required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "pageSize", value = "数量", dataType = "Integer"),
            @ApiImplicitParam(paramType = "query",name = "pageNum", value = "页码", dataType = "Integer"),
    })
    @GetMapping("/coupons")
    public AjaxResult couponList(){
        ShopUserOpenid shopUserOpenid = shopUserIdByToken();

        startPage();
        List<ShopCouponVo> list = shopCouponService.selectJoinShopCouponByUserId(shopUserOpenid.getUserId());
        return AjaxResult.success(list);
    }


    /**
     * 新商品信息
     */
    @ApiOperation(value = "新商品信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "token", value = "用户token",required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "pageSize", value = "数量", dataType = "Integer"),
            @ApiImplicitParam(paramType = "query",name = "pageNum", value = "页码", dataType = "Integer"),
    })
    @GetMapping("/newGoods")
    public AjaxResult newGoodsList(){

        startPage();
        List<ShopProductSimpleVo> list = shopProductService.selectNewShopProduct();
        return AjaxResult.success(list);
    }

    /**
     * 热销商品
     */
    @ApiOperation(value = "热销商品")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "token", value = "用户token",required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "pageSize", value = "数量", dataType = "Integer"),
            @ApiImplicitParam(paramType = "query",name = "pageNum", value = "页码", dataType = "Integer"),
    })
    @GetMapping("/hotGoods")
    public AjaxResult hotGoodsList(){

        startPage();
        List<ShopProductSimpleVo> list = shopProductService.selectHotShopProduct(5);
        return AjaxResult.success(list);
    }  

    /**
     * 普通商品
     */
    @ApiOperation(value = "普通商品")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "token", value = "用户token",required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "pageSize", value = "数量", dataType = "Integer"),
            @ApiImplicitParam(paramType = "query",name = "pageNum", value = "页码", dataType = "Integer"),
    })
    @GetMapping("/goods")
    public AjaxResult goodsList(){
        startPage();
        List<ShopProductSimpleVo> list = shopProductService.selectShopProductAll();
        return AjaxResult.success(list);
    }


    /**
     * 特价商品
     */
    @ApiOperation(value = "特价商品")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "token", value = "用户token",required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "pageSize", value = "数量", dataType = "Integer"),
            @ApiImplicitParam(paramType = "query",name = "pageNum", value = "页码", dataType = "Integer"),
    })
    @GetMapping("/specialOffer")
    public AjaxResult specialOfferList(){
        startPage();
        List<ShopProductSimpleVo> list = shopProductService.selectIsSpecialShopProduct();
        return AjaxResult.success(list);
    }


    /**
     * 商品详细页面展示
     */
    @ApiOperation(value = "商品详细页面展示")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "token", value = "用户token",required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "productId", value = "产品Id", dataType = "Long"),
    })
    @GetMapping("/productInfo")
    public AjaxResult productInfo(@NotNull Long productId){
        ShopUserOpenid shopUserOpenid = shopUserIdByToken();

        ShopProductSimpleVo shopProduct = shopProductService.selectShopProductSimpleVoById(productId);

        //图片列表
        ShopProductImage paramImage = new ShopProductImage();
        paramImage.setProductId(productId);
        List<ShopProductImage> productImageList = shopProductImageService.selectShopProductImageList(paramImage);

        //购车中的数量
        ShopUserCart paramCart = new ShopUserCart();
        paramCart.setUserId(shopUserOpenid.getUserId());
        paramCart.setProductId(productId);
        List<ShopUserCart> userCartList = shopUserCartService.selectShopUserCartList(paramCart);
        if(userCartList.size() > 0){
            shopProduct.setCartQty(userCartList.get(0).getProductCount());
        }

        //收藏
        ShopUserFavorite paramFavorite = new ShopUserFavorite();
        paramFavorite.setTypeId(productId);
        paramFavorite.setUserId(shopUserOpenid.getUserId());
        List<ShopUserFavorite> favoriteList = shopUserFavoriteService.selectShopUserFavoriteList(paramFavorite);
        shopProduct.setFavorite(favoriteList.size() > 0);

        //评论
        List<ShopProductComment> commentList = shopProductCommentService.selectTop2ShopProductCommentByProductId(productId);

        //购物车数量
        Integer cartTotalQty = shopUserCartService.selectShopUserCartCountByUserId(shopUserOpenid.getUserId());

        AjaxResult ajaxResult = AjaxResult.success()
                .put("cartTotalQty", cartTotalQty)
                .put("shopProduct",shopProduct)
                .put("imageList", productImageList)
                .put("commentList", commentList);
        return ajaxResult;
    }

    /**
     * 商品评论
     */
    @ApiOperation(value = "商品评论")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token",required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "pageSize", value = "数量", dataType = "Integer"),
            @ApiImplicitParam(paramType = "query",name = "pageNum", value = "页码", dataType = "Integer"),
    })
    @GetMapping("/product/comment")
    public AjaxResult ProductComment(Long productId){

        ShopProductComment param = new ShopProductComment();
        param.setProductId(productId);
        param.setPid(0L);

        startPage();
        List<ShopProductComment> commentList = shopProductCommentService.selectShopProductCommentList(param);
        return AjaxResult.success(commentList);
    }


    /**
     * 商品分类
     */
    @ApiOperation(value = "商品分类")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token",required = true, dataType = "String"),
    })
    @GetMapping("/category")
    public AjaxResult category(){

        ShopProductCategory param = new ShopProductCategory();
        param.setType("1"); //分类  如果很多就采取分页
        List<ShopProductCategory> productCategoryList = shopProductCategoryService.selectShopProductCategoryList(param);
        return AjaxResult.success(productCategoryList);
    }

    /**
     * 分类下的商品
     */
    @ApiOperation(value = "分类下的商品")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "token", value = "用户token",required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "categoryId", value = "分类Id", dataType = "Long"),
            @ApiImplicitParam(paramType = "query",name = "pageSize", value = "数量", dataType = "Integer"),
            @ApiImplicitParam(paramType = "query",name = "pageNum", value = "页码", dataType = "Integer"),
    })
    @GetMapping("/category/product")
    public AjaxResult category(Long categoryId){
        //分页取 10
        startPage();

        List<ShopProductSimpleVo> shopProductBoList = shopProductService.selectJoinShopProductByCategoryId(categoryId);

        return AjaxResult.success(shopProductBoList);
    }


    /**
     * 加入收藏
     */
    @ApiOperation(value = "加入收藏")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token",required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "productId", value = "商品Id",required = true, dataType = "Long")
    })
    @GetMapping("/addFavorite")
    public AjaxResult addFavorite(Long productId) {
        ShopUserOpenid shopUserOpenid = shopUserIdByToken();

        ShopUserFavorite param = new ShopUserFavorite();
        param.setUserId(shopUserOpenid.getUserId());
        param.setTypeId(productId);
        List<ShopUserFavorite> userFavoriteList = shopUserFavoriteService.selectShopUserFavoriteList(param);
        if(userFavoriteList.size() > 0){
            return AjaxResult.success("已收藏过");
        } else{
            ShopProduct product = shopProductService.selectShopProductById(productId);
            ShopUserFavorite favorite = new ShopUserFavorite();
            favorite.setType(1);
            favorite.setUserId(shopUserOpenid.getUserId());
            favorite.setTypeId(productId);
            favorite.setTitle(product.getTitle());
            favorite.setThumbnail(product.getThumbnail());
            int rows = shopUserFavoriteService.insertShopUserFavorite(favorite);
            if(rows >0){
                return AjaxResult.success("收藏成功");
            } else {
                return AjaxResult.error("收藏失败");
            }
        }
    }


    /**
     * 取消收藏
     */
    @ApiOperation(value = "取消收藏")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token",required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "productId", value = "商品Id",required = true, dataType = "Long")
    })
    @GetMapping("/cancelFavorite")
    public AjaxResult cancelFavorite(Long productId) {
        ShopUserOpenid shopUserOpenid = shopUserIdByToken();

        ShopUserFavorite param = new ShopUserFavorite();
        param.setUserId(shopUserOpenid.getUserId());
        param.setTypeId(productId);
        List<ShopUserFavorite> userFavoriteList = shopUserFavoriteService.selectShopUserFavoriteList(param);
        if(userFavoriteList.size() > 0){
            int rows = shopUserFavoriteService.deleteShopUserFavoriteById(userFavoriteList.get(0).getId());
            if(rows >0){
                return AjaxResult.success("取消收藏成功");
            } else {
                return AjaxResult.error("取消收藏失败");
            }
        } else{
            return AjaxResult.error("取消收藏失败");
        }
    }
}
